import { defineClientConfig } from "@vuepress/client";

const categoryRouteMap: Record<string, string> = {
  "后端": "/categories/houduan/1/",
  "前端": "/categories/qianduan/1/",
  "优质项目": "/categories/youzhixiangmu/1/",
  "开发工具": "/categories/kaifagongju/1/",
  "面试大全": "/categories/mianshidaquan/1/",
  "公众号": "/categories/gongzhonghao/1/",
  "关于作者": "/categories/author/1/",
};

function linkifyPageInfo() {
  if (typeof window === "undefined") return;
  const info = document.querySelector(".page-info");
  if (!info) return;
  const items = info.querySelectorAll(".xicon-container .xicon-content");
  if (!items || items.length === 0) return;

  // Usually: [author, date, category, tag]
  items.forEach((el, index) => {
    const text = (el.textContent || "").trim();
    if (!text) return;

    // Convert category and tag (index >= 2) to links
    if (index >= 2) {
      const href = categoryRouteMap[text];
      if (!href) return;
      const parent = el.parentElement;
      if (!parent) return;
      // Avoid re-wrapping
      if (parent.querySelector("a")) return;

      const a = document.createElement("a");
      a.href = href;
      a.textContent = text;
      a.style.color = "inherit";
      a.style.textDecoration = "none";

      // Replace content node with anchor
      el.replaceWith(a);
    }
  });
}

function ensureBackButton() {
  if (typeof window === "undefined") return;
  const id = "reco-back-button";
  let btn = document.getElementById(id);
  if (!btn) {
    btn = document.createElement("button");
    btn.id = id;
    btn.className = "reco-back-button";
    btn.title = "返回";
    btn.innerText = "返回";
    btn.addEventListener("click", () => {
      if (history.length > 1) {
        history.back();
      } else {
        window.location.href = "/";
      }
    });
    document.body.appendChild(btn);
  }
  // 仅在文章内容页显示：当存在 .theme-reco-default-content 时
  const isArticle = !!document.querySelector(".theme-reco-default-content");
  (btn as HTMLButtonElement).style.display = isArticle ? "flex" : "none";
}

export default defineClientConfig({
  enhance({ router }) {
    if (!router) return;
    router.afterEach(() => {
      // Wait for DOM rendered
      setTimeout(() => {
        linkifyPageInfo();
        ensureBackButton();
      }, 0);
    });
  },
  setup() {
    if (typeof window !== "undefined") {
      window.addEventListener("load", () => {
        linkifyPageInfo();
        ensureBackButton();
      });
    }
  },
}); 